<template>
  <el-dialog
    :title="!dataForm.goodsId ? '新增' : '查看'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
    <el-form-item label="商铺分类" prop="userId">
      <el-select v-model="dataForm.userId" placeholder="商铺分类">
          <!-- <el-option
                v-for="item in dataForm.userIdOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
          </el-option> -->
        <el-option v-for="item in this.goodsClass" :key="item.userId" :label="item.className" :value="item.userId"></el-option>
	    </el-select>
    </el-form-item>    
    <el-form-item label="商品类型" prop="typeId">
      <el-select v-model="dataForm.typeId" placeholder="商品类型">
          <el-option
                v-for="item in dataForm.typeIdOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
          </el-option>
	  </el-select>
    </el-form-item>    
    <el-form-item label="商品名称" prop="goodsName">
      <el-input v-model="dataForm.goodsName" placeholder="商品名称" style="width:500px"></el-input>
    </el-form-item>
    <el-form-item label="商品主图" prop="goodsImg">
      <el-upload
      :action="this.$http.adornUrl(`/business/goods/uploadImg?token=${this.$cookie.get('token')}`)"
      :limit="1"
      list-type="picture-card"
      :file-list="dataForm.goodsImg"
      :on-preview="handlePreview"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-exceed="onExceed">
      <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="商品轮播图" prop="goodsDescImgs">
      <el-upload
      :action="this.$http.adornUrl(`/business/goods/uploadImg?token=${this.$cookie.get('token')}`)"
      :limit="3"
      list-type="picture-card"
      :file-list="dataForm.goodsDescImgs"
      :on-preview="handlePreview"
      :on-success="handleSuccess1"
      :on-remove="handleRemove1"
      :on-exceed="onExceed1">
      <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="商品条码" prop="barCode">
      <el-input v-model="dataForm.barCode" placeholder="商品条码" style="width:200px"></el-input>
    </el-form-item>
    <el-form-item label="商品编号" prop="goodsSn">
      <el-input v-model="dataForm.goodsSn" placeholder="商品编号" style="width:200px"></el-input>
    </el-form-item>
    <el-form-item label="推荐售价" prop="marketPrice">
      <el-input v-model="dataForm.marketPrice" placeholder="推荐售价" style="width:100px"></el-input>
    </el-form-item>
    <el-form-item label="推荐售价" v-if="dataForm.typeId === 3">
      <el-input value="0.01" placeholder="推荐售价" style="width:100px" disabled></el-input>
    </el-form-item>
    <el-form-item label="商品原价" prop="vipPrice" v-if="dataForm.typeId !== 3">
      <el-input v-model="dataForm.vipPrice" placeholder="商品原价" style="width:100px"></el-input>
    </el-form-item>
    <el-form-item label="兑换消耗（券）" prop="vipPrice" v-if="dataForm.typeId === 3">
      <el-input v-model="dataForm.vipPrice" placeholder="兑换消耗（券）" style="width:100px"></el-input>
    </el-form-item>
    <el-form-item label="商品剩余库存" prop="goodsStock" v-if="dataForm.goodsId !== 0">
      <el-input v-model="dataForm.goodsStock" placeholder="商品剩余库存" style="width:100px"></el-input>
    </el-form-item>
    <el-form-item label="商品初始库存" prop="initialInventory">
      <el-input v-model="dataForm.initialInventory" placeholder="商品初始库存" style="width:100px"></el-input>
    </el-form-item>
    <!-- <el-form-item label="是否新品" prop="isNewGoods">
      <el-radio-group v-model="dataForm.isNewGoods">
        <el-radio :label="1">是</el-radio>
        <el-radio :label="0">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="是否推荐商品" prop="isRecomGoods">
      <el-radio-group v-model="dataForm.isRecomGoods">
        <el-radio :label="1">是</el-radio>
        <el-radio :label="0">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="是否返佣" prop="isCommission">
      <el-radio-group v-model="dataForm.isCommission">
        <el-radio :label="1">是</el-radio>
        <el-radio :label="0">否</el-radio>
      </el-radio-group>
    </el-form-item>   
    <el-form-item label="佣金数量" prop="commission" v-if="dataForm.isCommission === 1">
      <el-input v-model="dataForm.commission" placeholder="佣金数量" style="width:100px"></el-input>
    </el-form-item>
    <el-form-item label="商品运费" prop="deliverMoney">
      <el-input v-model="dataForm.deliverMoney" placeholder="商品运费" style="width:100px"></el-input>
    </el-form-item>
    <el-form-item label="配送方式" prop="distributionTypes">
      <el-radio-group v-model="dataForm.distributionTypes">
        <el-radio :label="-1">全部</el-radio>
        <el-radio :label="1">自取</el-radio>
        <el-radio :label="0">物流</el-radio>
        <el-radio :label="2">商家配送</el-radio>
      </el-radio-group>
    </el-form-item> -->
    <el-form-item label="商品描述" prop="goodsDesc">
      <el-input type="textarea" maxlength="200" show-word-limit v-model="dataForm.goodsDesc" placeholder="商品描述" style="width:500px; height: 100px"></el-input>
    </el-form-item>
    <el-form-item label="商品详情" prop="goodsDetails">
      <UEditor ref="ueditor" id='newsinfo'></UEditor>
      <!-- <UE :config=config ref="ue"></UE> -->
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import UEditor from '@/components/ueditor/ueditor.vue'
  export default {
    data () {
      return {
        isDisabled: false,
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        goodsClass: [],
        dataForm: {
          goodsId: 0,
          userId: '',
          typeId: '',
          goodsName: '',
          goodsImg: [],
          goodsimg: '',
          goodsDescImgs: [],
          descImg: [],
          goodsDesc: '',
          marketPrice: '',
          vipPrice: '',
          distributionTypes: '',
          isNewGoods: '',
          isRecomGoods: '',
          isCommission: '',
          commission: '',
          goodsStock: '',
          deliverMoney: '',
          initialInventory: '',
          goodsSn: '',
          barCode: '',
          userIdOptions: [{
            value: 373,
            label: '生鲜水果'
          }, {
            value: 374,
            label: '美食饮品'
          }, {
            value: 375,
            label: '生活服务'
          }, {
            value: 376,
            label: '丽人美妆'
          }, {
            value: 377,
            label: '家具建材'
          }, {
            value: 378,
            label: '超市便利'
          }, {
            value: 381,
            label: '休闲娱乐'
          }],
          typeIdOptions: [{
            value: 0,
            label: '自营商品'
          }, {
            value: 4,
            label: '新人专享'
          }]
        },
        dataRule: {
          userId: [
            { required: true, message: '商铺分类不能为空', trigger: 'blur' }
          ],
          typeId: [
            { required: true, message: '商品类型不能为空', trigger: 'blur' }
          ],
          goodsName: [
            { required: true, message: '商品名不能为空', trigger: 'blur' }
          ],
          goodsSn: [
            { required: true, message: '请输入商品编号', trigger: 'blur' }
          ],
          marketPrice: [
            { required: true, message: '推荐售价不能为空', trigger: 'blur' },
            { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '推荐售价不规范', trigger: 'blur' }
          ],
          vipPrice: [
            { required: true, message: '不能为空', trigger: 'blur' },
            { pattern: /^[0-9]+$/, message: '为正整数', trigger: 'blur' }
          ],
          goodsStock: [
            { pattern: /^[0-9]+$/, message: '商品剩余库存为正整数', trigger: 'blur' }
          ],
          initialInventory: [
            { required: true, message: '商品初始库存不能为空', trigger: 'blur' },
            { pattern: /^[0-9]+$/, message: '商品初始库存为正整数', trigger: 'blur' }
          ],
          // isNewGoods: [
          //   { required: true, message: '是否新品不能为空', trigger: 'blur' }
          // ],
          // isRecomGoods: [
          //   { required: true, message: '是否推荐商品不能为空', trigger: 'blur' }
          // ],
          // isCommission: [
          //   { required: true, message: '是否返佣不能为空', trigger: 'blur' }
          // ],
          // distributionTypes: [
          //   { required: true, message: '配送方式不能为空', trigger: 'blur' }
          // ],
          // commission: [
          //   { required: true, message: '佣金数量不能为空', trigger: 'blur' },
          //   { pattern: /^[0-9]+$/, message: '佣金数量为正整数', trigger: 'blur' }
          // ],
          // deliverMoney: [
          //   { required: true, message: '商品运费不能为空', trigger: 'blur' },
          //   { pattern: /^[0-9]+$/, message: '商品运费为正整数', trigger: 'blur' }
          // ],
          goodsDesc: [
            { required: true, message: '商品描述不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      UEditor
    },
    methods: {
      // 图片预览
      handlePreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.goodsImg.push({name: 'tupian', url: 'http://image.yilianbaihui.cn/consumer/goods/' + res.data})
          this.dataForm.goodsimg = res.data
        }
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        for (var i = 0; i < this.dataForm.goodsImg.length; i++) {
          var picc = this.dataForm.goodsImg[i]
          if (picc.url === file.url) {
            this.dataForm.goodsImg.splice(i, 1)
            this.dataForm.goodsimg = ''
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      },
      // 文件上传成功的钩子函数
      handleSuccess1 (res, file, fileList) {
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.goodsDescImgs.push({name: 'tupian', url: 'http://image.yilianbaihui.cn/consumer/goods/' + res.data})
          this.dataForm.descImg.push(res.data)
        }
      },
      // 删除文件之前的钩子函数
      handleRemove1 (file, fileList) {
        for (var i = 0; i < this.dataForm.goodsDescImgs.length; i++) {
          var picc = this.dataForm.goodsDescImgs[i]
          if (picc.url === file.url) {
            this.dataForm.goodsDescImgs.splice(i, 1)
            this.dataForm.descImg.splice(i, 1)
          }
        }
        // console.log(this.dataForm.imgs)
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed1 (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传3个图片',
          duration: 6000
        })
      },
      init (id) {
        this.dataForm.goodsImg = []
        this.dataForm.goodsimg = ''
        this.dataForm.goodsDescImgs = []
        this.dataForm.descImg = []
        this.$http({
          url: this.$http.adornUrl('/business/goods/getPrefabricatedGoodsClass'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.goodsClass = data.data
          }
        })
        this.dataForm.commission = ''
        this.dataForm.descImg = []
        this.dataForm.goodsId = id || 0
        this.dataForm.barCode = ''
        this.visible = true
        this.isDisabled = false
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.goodsId) {
            this.$http({
              url: this.$http.adornUrl(`/business/goods/getPrefabricatedGoodsById/${this.dataForm.goodsId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.goodsId = data.data.goodsId
                this.dataForm.userId = data.data.userId
                this.dataForm.typeId = data.data.typeId
                this.dataForm.goodsName = data.data.goodsName
                var pic = data.data.goodsImg
                if (pic !== null) {
                  this.dataForm.goodsImg.push({name: 'tupian', url: 'http://image.yilianbaihui.cn/consumer/goods/' + pic})
                }
                var pic1 = data.data.descImg
                for (var i = 0; i < pic1.length; i++) {
                  this.dataForm.goodsDescImgs.push({name: 'tupian', url: 'http://image.yilianbaihui.cn/consumer/goods/' + pic1[i]})
                  this.dataForm.descImg.push(pic1[i])
                }
                this.dataForm.goodsDesc = data.data.goodsDesc
                this.dataForm.marketPrice = data.data.marketPrice
                this.dataForm.vipPrice = data.data.vipPrice
                this.dataForm.distributionTypes = data.data.distributionTypes
                this.dataForm.isNewGoods = data.data.isNewGoods
                this.dataForm.isRecomGoods = data.data.isRecomGoods
                this.dataForm.isCommission = data.data.isCommission
                this.dataForm.commission = data.data.commission
                this.dataForm.goodsStock = data.data.goodsStock
                this.dataForm.deliverMoney = data.data.deliverMoney
                this.dataForm.initialInventory = data.data.initialInventory
                this.dataForm.goodsSn = data.data.goodsSn
                this.$refs.ueditor.setUEContent(data.data.goodsDetails)
                this.dataForm.barCode = data.data.barCode
              }
            })
          }
        })
      },
      goodsId (id) {
        console.log(id)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.isDisabled = true
            this.$http({
              url: this.$http.adornUrl(`/business/goods/${!this.dataForm.goodsId ? 'addPrefabricatedGoods' : 'modifyPrefabricatedGoodsById'}`),
              method: 'post',
              data: this.$http.adornData({
                'goodsId': this.dataForm.goodsId || undefined,
                'goodsName': this.dataForm.goodsName,
                'userId': this.dataForm.userId,
                'typeId': this.dataForm.typeId,
                'goodsImg': this.dataForm.goodsimg,
                'descImg': this.dataForm.descImg,
                'goodsDesc': this.dataForm.goodsDesc,
                'marketPrice': this.dataForm.marketPrice,
                'vipPrice': this.dataForm.vipPrice,
                'distributionTypes': this.dataForm.distributionTypes,
                'isNewGoods': this.dataForm.isNewGoods,
                'isRecomGoods': this.dataForm.isRecomGoods,
                'isCommission': this.dataForm.isCommission,
                'commission': this.dataForm.commission,
                'goodsStock': this.dataForm.goodsStock,
                'deliverMoney': this.dataForm.deliverMoney,
                'initialInventory': this.dataForm.initialInventory,
                'goodsSn': this.dataForm.goodsSn,
                'goodsDetails': this.$refs.ueditor.getUEContent(),
                'barCode': this.dataForm.barCode
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
